"""
缓存管理工具

提供缓存监控、清理和管理功能
"""

from typing import Dict, Any, Optional
from cache import Cache
import logging

logger = logging.getLogger(__name__)


class CacheManager:
    """缓存管理器"""
    
    def __init__(self, cache: Cache):
        self.cache = cache
    
    def get_stats(self) -> Dict[str, Any]:
        """获取缓存统计信息"""
        try:
            if hasattr(self.cache, 'get_stats'):
                return self.cache.get_stats()
            else:
                return {"error": "Cache implementation does not support stats"}
        except Exception as e:
            logger.error(f"Failed to get cache stats: {e}")
            return {"error": str(e)}
    
    def cleanup_expired(self):
        """手动触发过期数据清理"""
        try:
            if hasattr(self.cache, '_cleanup_expired'):
                self.cache._cleanup_expired()
                logger.info("Cache cleanup completed")
            else:
                logger.warning("Cache implementation does not support manual cleanup")
        except Exception as e:
            logger.error(f"Failed to cleanup cache: {e}")
    
    def clear_all(self):
        """清空所有缓存（谨慎使用）"""
        try:
            self.cache.clear()
            logger.warning("All cache cleared")
        except Exception as e:
            logger.error(f"Failed to clear cache: {e}")
    
    def get_memory_usage(self) -> Optional[int]:
        """获取缓存内存使用量（字节）"""
        try:
            import sys
            if hasattr(self.cache, 'cache'):
                return sys.getsizeof(self.cache.cache)
            return None
        except Exception as e:
            logger.error(f"Failed to get memory usage: {e}")
            return None
    
    def export_cache(self, output_file: str):
        """导出缓存数据到文件"""
        try:
            import json
            if hasattr(self.cache, 'cache'):
                with open(output_file, 'w', encoding='utf-8') as f:
                    # 只导出简单数据类型
                    exportable_data = {}
                    for id, fields in self.cache.cache.items():
                        exportable_data[id] = {}
                        for field, value in fields.items():
                            if isinstance(value, (str, int, float, bool, type(None))):
                                exportable_data[id][field] = value
                            else:
                                exportable_data[id][field] = str(value)
                    
                    json.dump(exportable_data, f, ensure_ascii=False, indent=2)
                logger.info(f"Cache exported to {output_file}")
            else:
                logger.warning("Cache implementation does not support export")
        except Exception as e:
            logger.error(f"Failed to export cache: {e}")
    
    def import_cache(self, input_file: str):
        """从文件导入缓存数据"""
        try:
            import json
            with open(input_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
                
            for id, fields in data.items():
                for field, value in fields.items():
                    self.cache.set(id, field, value)
            
            logger.info(f"Cache imported from {input_file}")
        except Exception as e:
            logger.error(f"Failed to import cache: {e}")


# 使用示例
if __name__ == "__main__":
    from cache import MemoryCache
    
    # 创建缓存实例
    cache = MemoryCache(max_size=100, default_ttl=600)
    
    # 创建管理器
    manager = CacheManager(cache)
    
    # 设置一些测试数据
    cache.set("test1", "name", "Alice")
    cache.set("test1", "age", 25)
    cache.set("test2", "name", "Bob")
    
    # 获取统计信息
    print("Cache Stats:", manager.get_stats())
    
    # 获取内存使用
    print("Memory Usage:", manager.get_memory_usage(), "bytes")
    
    # 导出缓存
    manager.export_cache("cache_backup.json")
    
    # 清理过期数据
    manager.cleanup_expired()
